﻿using System;
using System.ComponentModel;
using System.Windows.Forms;
using MetroFramework.Forms;
using DataTurnClient.Server;
using Splat;
using DataTurnClient.Interface;
using ReactiveUI;
using System.Reactive.Disposables;
using DataTurnClient.ViewModel;
using System.Reactive.Linq;
using System.Linq;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Configuration;

namespace DataTurnClient
{
    public partial class MainTurn : MetroForm, IViewFor<MainTurnViewModel>
    {
        object IViewFor.ViewModel
        {
            get => ViewModel;
            set => ViewModel = (MainTurnViewModel)value;
        }

        public MainTurnViewModel ViewModel { get; set; }


        public MainTurn()
        {
            InitializeComponent();
            Globals.DbType = (SqlSugar.DbType)Convert.ToInt32(ConfigurationManager.AppSettings["DbType"]);
            Globals.DbConnect = ConfigurationManager.AppSettings["DbConnect"];
            InitBindings();
            this.FormClosing += Form1_FormClosing;
            this.SizeChanged += Form1_SizeChanged;
            metroTabControl2.SelectedIndex = 0;
            System.Timers.Timer t1 = new System.Timers.Timer(1000);
            t1.Elapsed += new System.Timers.ElapsedEventHandler(AllRunTime);
            t1.AutoReset = true;
            t1.Enabled = true;
        }
        //////////////////////////////////////////////
        ///写在之前
        ///时间字符串规则
        ///0:00     用:分割，前面的代表时间类型，后面代表具体的value
        ///层级，列表0代表时，列表1代表分，列表2代表秒，列表3代表如果是之间类型，所要执行的时间
        ///时间类型代码，0-未启用，1-固定类型，2-循环类型，3-之间类型
        ///特殊说明。3-之间类型
        ///例：0:00,3:87,0:00,2:20
        ///此例为，在时间是早上8点到晚上7点之间，每20分钟循环执行
        ///例：1:01

        /// <summary>
        /// 同步任务定时器
        /// </summary>
        public System.Timers.Timer timer { get; set; } = new System.Timers.Timer();

        public Job CurrentJobRows { get => metroGrid1.CurrentRow == null ? new Job() : ViewModel.JobList[metroGrid1.CurrentRow.Index]; }

        public Log CurrentLogRows { get => metroGrid2.CurrentRow == null ? new Log() : ViewModel.LogList[metroGrid2.CurrentRow.Index]; }

        public TabPage AlPage { get; set; }

        public bool TabPass { get; set; } = false;

        public List<bool> CheckControl { get; set; } = new List<bool>() { false, false, false ,false,false,false,false};


        /// <summary>
        /// 绑定构造
        /// </summary>
        private void InitBindings()
        {
            Locator.CurrentMutable.RegisterLazySingleton<IDBHelperService>(() => new DBHelperService());
            Locator.CurrentMutable.RegisterLazySingleton<ITool>(() => new Tool());
            Locator.CurrentMutable.RegisterLazySingleton(() => new TimeService());
            Locator.CurrentMutable.RegisterLazySingleton(() => new LogService());
            Locator.CurrentMutable.RegisterLazySingleton(() => new MainTurn());
            ViewModel = new MainTurnViewModel(RxApp.MainThreadScheduler);
            this.WhenActivated(d =>
            {
                ///刷新配置
                this.BindCommand(ViewModel,
                      x => x.SelectSetCommand,
                      x => x.metroLink1)
                 .DisposeWith(d);

                this.BindCommand(ViewModel,
                      x => x.RunAllJobCommand,
                      x => x.全部执行一次ToolStripMenuItem)
                 .DisposeWith(d);

                this.BindCommand(ViewModel,
                      x => x.ClearLogGridCommand,
                      x => x.清理日志ToolStripMenuItem)
                 .DisposeWith(d);

                this.BindCommand(ViewModel,
                      x => x.SelectJobCommand,
                      x => x.刷新ToolStripMenuItem)
                 .DisposeWith(d);

                更改状态ToolStripMenuItem.Events().Click.Do(x =>
                {
                    ViewModel.ChangeJobStatusCommand.Execute(CurrentJobRows.JobCode).Subscribe();
                }).Subscribe();

                执行一次ToolStripMenuItem.Events().Click.Do(x =>
                {
                    ViewModel.RunJobCommand.Execute(CurrentJobRows.JobCode).Subscribe();
                }).Subscribe();

                metroGrid1.Events().DoubleClick.Do(x =>
                {
                    ViewModel.ShowJobMessageCommand.Execute(CurrentJobRows == null ? "" : CurrentJobRows.JobCode).Subscribe(Result => {
                        if (Result != "") { MessageBox.Show(Result); }
                    });
                }).Subscribe();

                metroGrid2.Events().DoubleClick.Do(x =>
                {
                    ViewModel.ShowLogMessageCommand.Execute(metroGrid2.CurrentRow == null ? 0 : metroGrid2.CurrentRow.Index).Subscribe(Result => {
                        if (Result != "") { MessageBox.Show(Result); }
                    });
                }).Subscribe();

                this.LableJobCode.Events().LostFocus.Do(x =>
                    ViewModel.CheckControlCommand.Execute(LableJobCode.Text).Subscribe(result =>
                    {
                        this.LableCode.Visible = result;
                        //firstSaveButton.Enabled = !result;
                        CheckControl[0] = !result;
                        firstSaveButton.Enabled = (CheckControl.Where(y => y == true).ToList().Count > 2);
                    })
                    ).Subscribe();

                this.LableJobName.Events().LostFocus.Do(x =>
                    ViewModel.CheckControlCommand.Execute(LableJobName.Text).Subscribe(result =>
                    {
                        this.LableName.Visible = result;
                        //firstSaveButton.Enabled = !result;
                        CheckControl[1] = !result;
                        firstSaveButton.Enabled = (CheckControl.Where(y => y == true).ToList().Count > 2);
                    })
                    ).Subscribe();

                this.LableJobDetail.Events().LostFocus.Do(x =>
                    ViewModel.CheckControlCommand.Execute(LableJobDetail.Text).Subscribe(result =>
                    {
                        this.LableMsg.Visible = result;
                        //firstSaveButton.Enabled = !result;
                        CheckControl[2] = !result;
                        firstSaveButton.Enabled = (CheckControl.Where(y => y == true).ToList().Count > 2);
                    })
                    ).Subscribe();

                this.LableJobPath.Events().LostFocus.Do(x =>
                    ViewModel.CheckControlCommand.Execute(LableJobPath.Text).Subscribe(result =>
                    {
                        this.metroLabel7.Visible = result;
                        //firstSaveButton.Enabled = !result;
                        secondSaveButton.Enabled = !result;
                        CheckControl[3] = !result;
                        secondSaveButton.Enabled = (CheckControl.Where(y => y == true).ToList().Count > 4);
                    })
                ).Subscribe();

                this.LableJobMode.Events().LostFocus.Do(x =>
                    ViewModel.CheckControlCommand.Execute(LableJobMode.Text).Subscribe(result =>
                    {
                        this.metroLabel15.Visible = result;
                        //firstSaveButton.Enabled = !result;
                        secondSaveButton.Enabled = !result;
                        CheckControl[4] = !result;
                        secondSaveButton.Enabled = (CheckControl.Where(y => y == true).ToList().Count > 4);
                    })
                ).Subscribe();

                this.LableJobWeek.Events().LostFocus.Do(x =>
                    ViewModel.CheckControlCommand.Execute(LableJobWeek.Text).Subscribe(result =>
                    {
                        this.metroLabel15.Visible = result;
                        //firstSaveButton.Enabled = !result;
                        thirdSaveButton.Enabled = !result;
                        CheckControl[5] = !result;
                        thirdSaveButton.Enabled = (CheckControl.Where(y => y == true).ToList().Count > 6);
                    })
                ).Subscribe();

                this.LableJobTimeString.Events().LostFocus.Do(x =>
                    ViewModel.CheckControlCommand.Execute(LableJobTimeString.Text).Subscribe(result =>
                    {
                        this.metroLabel15.Visible = result;
                        //firstSaveButton.Enabled = !result;
                        thirdSaveButton.Enabled = !result;
                        CheckControl[6] = !result;
                        thirdSaveButton.Enabled = (CheckControl.Where(y => y == true).ToList().Count > 6);
                    })
                ).Subscribe();

                this.secondSaveButton.Events().Click.Do(x =>
               {
                   ViewModel.CreateJob.JobRoute = ComboxJobRoute.SelectedValue.ToString().Split('-')[0].ToString() + ":" + LableJobPath.Text;
                   ViewModel.UpdateJobCommand.Execute(ViewModel.CreateJob).Subscribe(result =>
                   {
                       if (result.Success)
                       {
                           MessageBox.Show($"保存失败{result.Message}");
                       }
                       else
                       {
                           HandoffTab();
                       }
                   });
                    }).Subscribe();

                this.thirdSaveButton.Events().Click.Do(x =>
                {
                    ViewModel.UpdateJobCommand.Execute(ViewModel.CreateJob).Subscribe(result =>
                    {
                        if (result.Success)
                        {
                            HandoffTab();
                            ViewModel.SelectOneJobCommand.Execute(ViewModel.CreateJob.JobCode).Subscribe(res =>
                            {
                                if (res.Success)
                                {
                                    res.Data.JobRunStatus = Job.JobRunType.Wating;
                                    ViewModel.CreateJob = new Job();
                                    ViewModel.AddJobList.Add(res.Data);
                                    ViewModel.SelectJobCommand.Execute();
                                }
                            });
                        }
                    });
                    }).Subscribe();

                this.fourthSaveButton.Events().Click.Do(x =>
                {
                    HandoffTab();
                }).Subscribe();

                this.firstSaveButton.Events().Click.Do(x =>
                {
                    ViewModel.AddJobCommand.Execute(ViewModel.CreateJob).Subscribe(result =>
                    {
                        if (result.Success)
                        {
                            MessageBox.Show($"无保存{result.Message}");
                        }
                        else
                        {
                            HandoffTab();
                        }
                    });
                    }
                    ).Subscribe();

                // 初始化启动
                this.Events().Load.Subscribe(e =>
                {
                    ViewModel.SelectJobCommand.Execute().Subscribe();
                    ViewModel.SelectSetCommand.Execute().Subscribe();
                    CheckForIllegalCrossThreadCalls = false;
                });

                // 任务数据源绑定
                this.OneWayBind(ViewModel,
                    vm => vm.JobList,
                    v => v.metroGrid1.DataSource)
                    .DisposeWith(d);

                // 日志数据源绑定
                this.OneWayBind(ViewModel,
                    vm => vm.LogList,
                    v => v.metroGrid2.DataSource)
                    .DisposeWith(d);

                // 添加数据完预览视图绑定
                this.OneWayBind(ViewModel,
                    vm => vm.AddJobList,
                    v => v.metroGrid3.DataSource)
                    .DisposeWith(d);

                // 添加数据完预览视图绑定
                this.OneWayBind(ViewModel,
                    vm => vm.CheckRouteList,
                    v => v.ComboxJobRoute.DataSource)
                    .DisposeWith(d);

                //管理数据源绑定
                this.OneWayBind(ViewModel,
                    vm => vm.SelectList,
                    v => v.metroComboBox1.DataSource)
                    .DisposeWith(d);

                // 定时器勾选绑定
                this.Bind(ViewModel,
                    vm => vm.IsTimer,
                    v => v.metroCheckBox5.Checked)
                    .DisposeWith(d);

                //时间字符串预览
                this.Bind(ViewModel,
                    vm => vm.CreateJob.JobRunTime,
                    v => v.LableJobTime.Text)
                    .DisposeWith(d);

                this.Bind(ViewModel,
                    vm => vm.JobTimeString,
                    v => v.LableJobTimeString.Text)
                    .DisposeWith(d);

                this.OneWayBind(ViewModel,
                    vm => vm.JobTimeString,
                    v => v.LableJobTime.Text)
                    .DisposeWith(d);

                this.Bind(ViewModel,
                    vm => vm.CreateJob.JobCode,
                    v => v.LableJobCode.Text)
                    .DisposeWith(d);
                
                this.Bind(ViewModel,
                    vm => vm.CreateJob.JobName,
                    v => v.LableJobName.Text)
                    .DisposeWith(d);

                this.Bind(ViewModel,
                    vm => vm.CreateJob.JobDetail,
                    v => v.LableJobDetail.Text)
                    .DisposeWith(d);

                this.Bind(ViewModel,
                    vm => vm.CreateJob.JobWeek,
                    v => v.LableJobWeek.Text)
                    .DisposeWith(d);

                this.Bind(ViewModel,
                    vm => vm.CreateJob.JobMode,
                    v => v.LableJobMode.Text)
                    .DisposeWith(d);

            });
        }

        /*------系统方法------*/

        /*------任务------*/
        /// <summary>
        /// 定时器专用执行方法
        /// </summary>
        /// <param name="sender"></param>
        private void AllRunTime(object sender, EventArgs e)
        {
            ViewModel.IsRunTimeCommand.Execute().Subscribe();
        }
        /*------任务------*/

        /*------系统事件------*/
        private void Form1_FormClosing(object sender, System.Windows.Forms.FormClosingEventArgs e)
        {
            if (MessageBox.Show("是否确认退出程序？", "退出", MessageBoxButtons.OKCancel, MessageBoxIcon.Question) == DialogResult.OK)
            {
                // 关闭所有的线程
                this.Dispose();
                this.Close();
            }
            else
            {
                e.Cancel = true;
            }
        }

        private void Form1_SizeChanged(object sender, System.EventArgs e)
        {
            //判断是否选择的是最小化按钮
            if (WindowState == FormWindowState.Minimized)
            {
                //隐藏任务栏区图标
                this.ShowInTaskbar = false;
                //图标显示在托盘区
                notifyIcon1.Visible = true;
                this.Visible = false;
            }
        }

        private void notifyIcon1_MouseDoubleClick(object sender, System.EventArgs e)
        {
            if (WindowState == FormWindowState.Minimized)
            {
                //还原窗体显示    
                WindowState = FormWindowState.Normal;
                //激活窗体并给予它焦点
                this.Activate();
                //任务栏区显示图标
                this.ShowInTaskbar = true;
                //托盘区图标隐藏
                notifyIcon1.Visible = false;
                this.Visible = true;
            }
        }
        /*------系统事件------*/

        /*------右键方法------*/

        private void 关闭ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (MessageBox.Show("是否确认退出程序？", "退出", MessageBoxButtons.OKCancel, MessageBoxIcon.Question) == DialogResult.OK)
            {
                // 关闭所有的线程
                this.Dispose();
                this.Close();
            }
        }

        private void 显示ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (WindowState == FormWindowState.Minimized)
            {
                //还原窗体显示    
                WindowState = FormWindowState.Normal;
                //激活窗体并给予它焦点
                this.Activate();
                //任务栏区显示图标
                this.ShowInTaskbar = true;
                //托盘区图标隐藏
                notifyIcon1.Visible = false;
                this.Visible = true;
            }
        }


            private void metroLink2_Click(object sender, EventArgs e)
        {
            Form2 form2 = new Form2();
            form2.Show();
        }//定时器设置事件

        private void HandoffTab()
        {
            AlPage = metroTabControl2.SelectedTab;
            int pageCount = metroTabControl2.TabPages.Count;
            TabPage page = metroTabControl2.SelectedTab;//获取当前选中的选项卡
            int indexPage = metroTabControl2.TabPages.IndexOf(page);
            TabPass = true;
            metroTabControl2.SelectedIndex = (indexPage + 1) == pageCount ? 0 : indexPage + 1;
            AlPage = metroTabControl2.SelectedTab;
        }

        private void metroTabControl2_Selecting(object sender, TabControlCancelEventArgs e)
        {
            //主要实现禁用切换tab页
            AlPage = AlPage == null ? this.metroTabPage1 : AlPage;
            TabPage page = metroTabControl2.SelectedTab;//获取当前选中的选项卡
            if (page != AlPage && TabPass == false)
            {
                int indexPage = metroTabControl2.TabPages.IndexOf(AlPage);
                metroTabControl2.SelectedIndex = indexPage;
            }
            else
            {
                metroTabControl2.SelectedIndex = e.TabPageIndex;
            }
            TabPass = false;
            
        }
    }
}
